// Package _2_AddTwoNumbers
// Date        : 2022/12/5 14:51
// Version     : 1.0.0
// Author      : 代码小学生王木木
// Email       : 18574945291@163.com
// Description :
package main

//Definition for singly-linked list.
type ListNode struct {
	Val  int
	Next *ListNode
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	if l1 == nil && l2 == nil {
		return nil
	}
	if l1 == nil {
		return l2
	}
	if l2 == nil {
		return l1
	}
	header := &ListNode{}
	ans := header
	up := 0
	for l1 != nil && l2 != nil {
		temp := l1.Val + l2.Val + up
		if temp >= 10 {
			temp = temp % 10
			up = 1
		} else {
			up = 0
		}
		ans.Next = &ListNode{
			Val: temp,
		}
		l1 = l1.Next
		l2 = l2.Next
		ans = ans.Next
	}
	for l1 != nil {
		temp := l1.Val + up
		if temp >= 10 {
			temp = temp % 10
			up = 1
		} else {
			up = 0
		}
		ans.Next = &ListNode{
			Val: temp,
		}
		l1 = l1.Next
		ans = ans.Next
	}
	for l2 != nil {
		temp := l2.Val + up
		if temp >= 10 {
			temp = temp % 10
			up = 1
		} else {
			up = 0
		}
		ans.Next = &ListNode{
			Val: temp,
		}
		l2 = l2.Next
		ans = ans.Next
	}
	// 最后特殊情况，如果算完还有进位的话，记得加上
	if up == 1 {
		ans.Next = &ListNode{
			Val: 1,
		}
	}

	return header.Next
}
